﻿var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var compress = require('compression');
var fs = require('fs');
var Wechat = require('./wechat.js');
var cookieParser = require("cookie-parser");
var admin = require('./routes/admin.js.js');
var Oracledb = require("./db/Oracledb.js");
var Msdb = require("./db/Msdb.js");
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');
const nodeExcel = require('excel-export');
var Excel = require('exceljs');
var Redisdb = require("./db/Redisdb.js");
const log = require('./logger.js');
var logger = require('./logger.js').logger;
const crypto = require('crypto');
var request = require("request");
const cors = require('cors');
const nodemailer = require('nodemailer');//对nodemailer模块进行导入
const Schedule = require('node-schedule');
const { ygdaSync, bmSync } = require('./ihr.js');
const secret = 'cxcx';
var Mysqldb = require('./db/Mysqldb.js');
const { checkbysql } = require('./routes/adminroute/qb/server_util.js');
const { api_gd_to_gylx } = require('./shzt.js');

log.use(app);
//手动记录，可以代替console.log
logger.info('test info 1');

// app.use(function(req,res,next){  
//     console.log("referer---"+req.headers.referer);  
//     if(req.headers.referer!="http://yunqiao.sserbpo.com/manage/"||req.headers.referer!="http://yunqiao.sserbpo.com/"||req.headers.referer!="http://localhost:7788/"||req.headers.referer!="http://47.98.191.71"
//       ||req.headers.referer!="http://47.98.191.71:8089"||req.headers.referer!="http://yunqiao.sserbpo.com:8089")
//     { console.log("referer可信")    

//       next(); 
// }
//   else{ 
//     console.log("referer不可信")
//       res.status(401).send('无效referer');  
//    }
// });  
app.use(function (err, req, res, next) {
  //当token验证失败时会抛出如下错误

  if (err.name === 'UnauthorizedError') {
    //这个需要根据自己的业务逻辑来处理（ 具体的err值 请看下面）
    console.log("无效权限")
    console.log("err  " + JSON.stringify(err))
    res.status(401).send('invalid token...');
  }
});

// 允许多个特定域名和端口跨域请求
app.use(cors({
  origin: "*"
}));
app.use(compress());
// app.use(express.static("../opt"));
// app.use(express.static("dist"));
// app.use(express.static("dist2"));
// app.use(express.static("dist-cache"));
// app.use(express.static("uploads"));
app.use(bodyParser.json({ limit: '50mb' })); // for parsing application/json
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(cookieParser());
//路由模块化
app.use('/admin', admin);

app.get('/getjsiticket', async function (req, res) {

  res.send("0000000")
})

async function tbjsshipSRM_util() {
  logger.info("同步即时库存开始");
  var posturl = "http://111.77.154.58:2233/jeecg-boot/qbxsckd/qbXsckd/getjsshipSRM_history";
  var db = new Msdb();
  request({
    url: posturl,
    method: "POST",
    json: true,
    headers: {
      "content-type": "application/json;charset=UTF-8",
    },
    body: {}
  }, async function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var rtarr = body.result

      var getnectvalsql = `select next value for seq_id as xlm`
      var lsmstr = await db.query(getnectvalsql);
      var xlm = lsmstr.recordsets[0][0].xlm;
      await db.insertData_jskcb(xlm, rtarr);
      await db.update(`update qb_jskcb set create_time =getdate()`)
      var mergesdql = `merge into qb_jskcb  a
using qb_fqbq  b
on a.bh=b.bh
when matched 
then update set a.phly='MES',a.kfkh=b.kfkh,a.zldj=b.qcdj,a.hbxx=b.hbxx;`
      var merges = await db.update(mergesdql)

      var mergehistoryupdatesql = `   
merge into qb_fqbq_history A  using (select * from qb_jskcb where dbq like '%F%') B
ON A.DBQ=B.DBQ AND A.BH=B.BH
WHEN MATCHED THEN 
UPDATE SET A.WLBM=B.WLBM
WHEN NOT MATCHED
THEN INSERT  (create_time,ID,WLMC,WLBM,BH,FDWKCL,JBKCL,PHLY,ifbd,gx,dy,jc,dj,ggxh,ck,xbq,dbq,lx) values
(getdate(),b.dbq+'-'+b.BH,b.WLMC,b.WLBM,b.BH,b.FDWKCL,b.JBKCL,b.PHLY,b.ifbd,b.gx,b.dy,b.jc,b.dj,ggxh,b.ck,b.xbq,b.dbq,'老mes');
`

      var updjbmydpsql = `update qb_fqbq_history set djbm='401',dj='优等品' where wlbm like '%401%'`
      var updjbmhgpsql = `update qb_fqbq_history set djbm='402',dj='合格品' where wlbm like '%402%'`
      //自动计算卷长
      var jsjcsql = `update qb_fqbq_history set jc=CONVERT(DECIMAL(18,2),fdwkcl)/CONVERT(DECIMAL(18,2),kd)*1000 where jc='0';`


      var updatezljcsql = `merge into qb_fqbq a using qb_jskcb b
          on a.bh=b.bh and a.khmb !='盘带模板' 
          when matched then 
          update set a.changdu=b.jc,a.bqzl=b.jbkcl,a.rkck=b.ck,a.fdwkcl=b.fdwkcl;`
      await db.update(mergehistoryupdatesql)
      await db.update(updjbmydpsql)
      await db.update(updjbmydpsql)
      await db.update(jsjcsql)
      await db.update(updatezljcsql)


      logger.info("同步已完成");
    } else {
    }
  })

}

//测试邮箱
async function sendemailtoadmin(text) {
  var user = '1584824430@qq.com' //自己的邮箱
  var pass = "oppnaqohqyiwhiif" //qq邮箱的授权码
  var recipient = '1584824430@qq.com' //接收人邮箱
  let transporter = nodemailer.createTransport({
    host: 'smtp.qq.com',
    port: 587,
    secure: false,
    auth: {
      user: user,
      pass: pass
    }
  })
  let info = await transporter.sendMail({
    from: `发送人<${user}>`,
    to: `接收人<${recipient}>`,
    subject: '名字',
    text: text //发送邮箱的内容
  })
}

function format(bytes) {
  return (bytes / 1024 / 1024).toFixed(2) + 'MB';
}



/**
 * 同步t_process_template 到qb_gxmb 工序模板
 */
async function syn_to_qb_gxmb() {
  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id,
    CAST(create_user AS CHAR) AS create_user,CAST(update_user AS CHAR) AS update_user from t_process_template`)
    console.log(rtarr)

    for (var i = 0; i < rtarr.length; i++) {
      var { id, code, title, production_line, status, is_deleted, create_user, create_time,
        update_user, update_time } = rtarr[i]
      //mysql 日期转换为sql server日期
      var create_time = new Date(create_time).toISOString().slice(0, 19).replace('T', ' ');
      var update_time = new Date(update_time).toISOString().slice(0, 19).replace('T', ' ');
      var ifczid = await checkbysql(`select * from qb_gxmb where ID='${id}'`)
      if (!ifczid) {
        await db.update(`insert into qb_gxmb(ID,CODE,TITLE,PRODUCTION_LINE,STATUS,IS_DELETED,
     CREATE_by,CREATE_TIME,UPDATE_by,UPDATE_TIME) 
   values(${id},'${code}','${title}','${production_line}','${status}','${is_deleted}',
   '${create_user}','${create_time}','${update_user}','${update_time}')`)
      }
      else {
        await db.update(`update qb_gxmb set CODE='${code}',TITLE='${title}',PRODUCTION_LINE='${production_line}',
  STATUS='${status}',IS_DELETED='${is_deleted}',CREATE_by='${create_user}',CREATE_TIME='${create_time}',
    UPDATE_by='${update_user}',UPDATE_TIME='${update_time}' where ID='${id}'`)
      }
    }
    resolve(1)
  })
}

/**
 * 同步t_process_template_params 到 qb_gxmb_mx 工序模板
 */
async function syn_to_qb_gxmb_mx() {
  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id,
  CAST(template_id AS CHAR) AS template_id  from t_process_template_params`)
    for (var i = 0; i < rtarr.length; i++) {
      var { id, template_id, param_name, param_code, unit, max_value, min_value, default_value } = rtarr[i]
      var ifczid = await checkbysql(`select * from qb_gxmb_mx where ID='${id}'`)
      if (!ifczid) {
        await db.update(`insert into qb_gxmb_mx(ID,mainid,PARAM_NAME,PARAM_CODE,UNIT,MAX_VALUE,MIN_VALUE,
        DEFAULT_VALUE) values('${id}','${template_id}','${param_name}','${param_code}','${unit}','${max_value}',
  '${min_value}','${default_value}')`)
      }
      else {
        await db.update(` update qb_gxmb_mx set PARAM_NAME='${param_name}',PARAM_CODE='${param_code}',UNIT='${unit}',
  MAX_VALUE='${max_value}',MIN_VALUE='${min_value}',DEFAULT_VALUE='${default_value}' where ID='${id}'`)
      }
    }
    resolve(1)
  })
}

/**
 * t_technique 到 qb_gy 工艺
 */
async function syn_to_qb_gy() {
  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id,CAST(process_template_id AS CHAR) AS process_template_id,
    CAST(create_user AS CHAR) AS create_user,CAST(update_user AS CHAR) AS update_user  from t_technique`)
    for (var i = 0; i < rtarr.length; i++) {
      var { id, code, title, process_template_id, status, is_deleted, create_user, create_time,
        update_user, update_time } = rtarr[i]
      //mysql 日期转换为sql server日期
      var create_time = new Date(create_time).toISOString().slice(0, 19).replace('T', ' ');
      var update_time = new Date(update_time).toISOString().slice(0, 19).replace('T', ' ');
      var ifczid = await checkbysql(`select * from qb_gy where ID='${id}'`)
      if (!ifczid) {
        await db.update(`insert into qb_gy(ID,CODE,TITLE,gxmbid,STATUS,IS_DELETED,
     CREATE_by,CREATE_TIME,UPDATE_by,UPDATE_TIME) 
   values(${id},'${code}','${title}','${process_template_id}','${status}','${is_deleted}',
   '${create_user}','${create_time}','${update_user}','${update_time}')`)
      }
      else {
        await db.update(`update qb_gy set CODE='${code}',TITLE='${title}',gxmbid='${process_template_id}',
  STATUS='${status}',IS_DELETED='${is_deleted}',CREATE_by='${create_user}',CREATE_TIME='${create_time}',
    UPDATE_by='${update_user}',UPDATE_TIME='${update_time}' where ID='${id}'`)
      }
    }
    resolve(1)
  })
}

/**
 * 同步 t_technique_params {id
technique_id
process_template_param_id
config_value
tolerance
remark
} 到 qb_gy_mx 工艺明细
 */
async function syn_to_qb_gy_mx() {
  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id,
  CAST(process_template_param_id AS CHAR) AS process_template_param_id,
  CAST(technique_id AS CHAR) AS technique_id  from t_technique_params`)
    for (var i = 0; i < rtarr.length; i++) {
      var { id, technique_id, process_template_param_id, config_value, tolerance, remark } = rtarr[i]
      var ifczid = await checkbysql(`select * from qb_gy_mx where ID='${id}'`)
      if (!ifczid) {
        await db.update(` insert into qb_gy_mx(ID,mainid,gxmbmxid,config_value,tolerance,remark)
       values('${id}','${technique_id}','${process_template_param_id}','${config_value}','${tolerance}','${remark}')`)
      }
      else {
        await db.update(` update qb_gy_mx set gxmbmxid='${process_template_param_id}',
      config_value='${config_value}',tolerance='${tolerance}',remark='${remark}' where ID='${id}'`)
      }
    }
    resolve(1)
  })
}

/**
 * 同步 t_technique_route 到qb_gylx 工艺路线
 */
async function syn_to_qb_gylx() {
  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id,
    CAST(create_user AS CHAR) AS create_user,CAST(update_user AS CHAR) AS update_user  from t_technique_route`)
    for (var i = 0; i < rtarr.length; i++) {
      var { id, code, title, production_line, category, remark, is_deleted, create_user, create_time,
        update_user, update_time, status, issue_status, quality_standard, gen_return, attach } = rtarr[i]
      //mysql 日期转换为sql server日期
      var create_time = new Date(create_time).toISOString().slice(0, 19).replace('T', ' ');
      var update_time = new Date(update_time).toISOString().slice(0, 19).replace('T', ' ');
      var ifczid = await checkbysql(`select * from qb_gylx where ID='${id}'`)
      if (!ifczid) {
        await db.update(`insert into qb_gylx(ID,CODE,TITLE,CATEGORY,REMARK,IS_DELETED,
     CREATE_by,CREATE_TIME,UPDATE_by,UPDATE_TIME,production_line,status,issue_status,quality_standard,gen_return,attach) 
   values(${id},'${code}','${title}','${category}','${remark}','${is_deleted}',
   '${create_user}','${create_time}','${update_user}','${update_time}','${production_line}','${status}','${issue_status}'
   ,'${quality_standard === null ? "" : quality_standard}','${gen_return}','${attach}')`)
      }
      else {
        await db.update(` update qb_gylx set CODE='${code}',TITLE='${title}',CATEGORY='${category}',status='${status}',
        issue_status='${issue_status}',REMARK='${remark}',IS_DELETED='${is_deleted}',CREATE_by='${create_user}',CREATE_TIME='${create_time}',
    UPDATE_by='${update_user}',UPDATE_TIME='${update_time}',production_line='${production_line}',attach='${attach}'
    ,quality_standard='${quality_standard === null ? "" : quality_standard}',gen_return='${gen_return}' where ID='${id}'`)
      }
    }
    resolve(1)
  })
}

/**
 * 同步 t_technique_route_detail 
到 qb_gylx_mx 工艺路线明细
 */
async function syn_to_qb_gylx_mx() {
  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id,
  CAST(route_id AS CHAR) AS route_id,CAST(technique_id AS CHAR) AS technique_id  from t_technique_route_detail`)
    for (var i = 0; i < rtarr.length; i++) {
      var { id, route_id, technique_id, sort } = rtarr[i]
      var ifczid = await checkbysql(`select * from qb_gylx_mx where ID='${id}'`)
      if (!ifczid) {
        await db.update(` insert into qb_gylx_mx(ID,mainid,technique_id,sort)
       values( '${id}','${route_id}','${technique_id}','${sort}')`)
      }
      else {
        await db.update(` update qb_gylx_mx set technique_id='${technique_id}',sort='${sort}' where ID='${id}'`)
      }
    }
    resolve(1)
  })
}

/**
 * 同步 t_technique_command_issue 到 qb_gyzlxf 工艺指令下发
 */
 async function syn_to_qb_gyzlxf() {
  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id,
    CAST(create_user AS CHAR) AS create_user,CAST(route_id AS CHAR) AS route_id,CAST(formula_id AS CHAR) AS formula_id 
    from t_technique_command_issue`)
    for (var i = 0; i < rtarr.length; i++) {
      var { id, command_code, route_id, issue_status, work_order, production_status, technique_level, create_user, create_time, formula_id,
        update_time, update_user, quality_standard, gen_return, attach, is_deleted } = rtarr[i]
      //mysql 日期转换为sql server日期
      var create_time = new Date(create_time).toISOString().slice(0, 19).replace('T', ' ');
      var update_time = new Date(update_time).toISOString().slice(0, 19).replace('T', ' ');
      var ifczid = await checkbysql(`select * from qb_gyzlxf where ID='${id}'`)
      if (!ifczid) {
        await db.update(` insert into qb_gyzlxf(id, command_code, route_id, issue_status,
           work_order ,production_status, technique_level, create_by, create_time,update_by,update_time,formula_id,quality_standard,gen_return,attach,is_deleted )
   values( '${id}', '${command_code}', '${route_id}', '${issue_status}', '${work_order}', '${production_status}', '${technique_level}',
    '${create_user}', '${create_time}','${update_user}', '${update_time}', '${formula_id}','${quality_standard}','${gen_return}','${attach}','${is_deleted}'
           )`)
      }
      else {
        await db.update(` update qb_gyzlxf set command_code='${command_code}',route_id='${route_id}',
        issue_status='${issue_status}',work_order='${work_order}',production_status='${production_status}',
        technique_level='${technique_level}',create_by='${create_user}',create_time='${create_time}',
        update_by='${update_user}',update_time='${update_time}',formula_id='${formula_id}',attach='${attach}'
        ,quality_standard='${quality_standard}',gen_return='${gen_return}',is_deleted='${is_deleted}'
        where id='${id}'`)
      }
    }
    resolve(1)
  })
}

 async function syn_to_qb_gyzlxf_mx() {

  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id,
  CAST(command_id AS CHAR) AS command_id from t_technique_command_issue_detail
  where id>1749993286946308096`)
    for (var i = 0; i < rtarr.length; i++) {
      var { id, command_id } = rtarr[i]
      let route_json = JSON.stringify(rtarr[i].route_json)
      let formula_json = JSON.stringify(rtarr[i].formula_json)
      var ifczid = await checkbysql(`select * from qb_gyzlxf_mx where ID='${id}'`)
      if (!ifczid) {
        await db.update(` insert into qb_gyzlxf_mx(ID,command_id,route_json,formula_json)
       values( '${id}','${command_id}','${route_json}','${formula_json}')`)


        var formula_jsonobj = JSON.parse(formula_json)
        let acstr = ''
        let bcstr = ''
        let ccstr = ''

        if (formula_jsonobj[0].designList) {
          formula_jsonobj[0].designList.map((item, index) => {
            var newitem = JSON.parse(item.designJson)
            if (newitem.A !== undefined) {
              newitem.A != 0 ? acstr = acstr + " " + newitem.A + '%' + item.category + " +" : ""
            } else;
            if (newitem.B !== undefined) {
              newitem.B != 0 ? bcstr = bcstr + " " + newitem.B + '%' + item.category + " +" : ""
            } else;
            if (newitem.C !== undefined) {
              newitem.C != 0 ? ccstr = ccstr + " " + newitem.C + '%' + item.category + " +" : ""
            } else;
          })
          //去掉最后的加号
          acstr = acstr.replace(/(.*?)\+([^+]*)$/, "$1$2");
          bcstr = bcstr.replace(/(.*?)\+([^+]*)$/, "$1$2");
          ccstr = ccstr.replace(/(.*?)\+([^+]*)$/, "$1$2");
        }
        else {

        }

        await db.update(`update qb_gyzlxf set AC='${acstr}',Bc='${bcstr}',Cc='${ccstr}',gg='${formula_jsonobj[0].productionSpecification}' where ID='${command_id}'`)




      }
      else {

        var formula_jsonobj = JSON.parse(formula_json)
        let [acstr, bcstr, ccstr] = ['', '', '']
        if (formula_jsonobj[0].designList) {
          formula_jsonobj[0].designList.map((item, index) => {
            var newitem = JSON.parse(item.designJson)
            if (newitem.A !== undefined) {
              newitem.A != 0 ? acstr = acstr + " " + newitem.A + '%' + item.category + " +" : ""
            } else;
            if (newitem.B !== undefined) {
              newitem.B != 0 ? bcstr = bcstr + " " + newitem.B + '%' + item.category + " +" : ""
            } else;
            if (newitem.C !== undefined) {
              newitem.C != 0 ? ccstr = ccstr + " " + newitem.C + '%' + item.category + " +" : ""
            } else;
          })
          acstr = acstr.substring(0, acstr.length - 1)
          bcstr = bcstr.substring(0, bcstr.length - 1)
          ccstr = ccstr.substring(0, ccstr.length - 1)
        }
        else {
          //去掉最后的加号


        }

        await db.update(`update qb_gyzlxf set AC='${acstr}',Bc='${bcstr}',Cc='${ccstr}',gg='${formula_jsonobj[0].productionSpecification}' where ID='${command_id}'`)

        await db.update(` update qb_gyzlxf_mx set command_id='${command_id}',route_json='${route_json}',formula_json='${formula_json}'
        where ID='${id}'`)


      }
    }
    resolve(1)
  })
}

async function syn_to_qb_sys_user() {
  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id,
    CAST(create_user AS CHAR) AS create_user ,CAST(update_user AS CHAR) AS update_user from sys_user`)
    for (var i = 0; i < rtarr.length; i++) {
      var { id, create_user, create_time, update_user, update_time, nick_name, real_name, status, is_deleted,
        phone, user_type, remark } = rtarr[i]
      //mysql 日期转换为sql server日期
      var create_time = new Date(create_time).toISOString().slice(0, 19).replace('T', ' ');
      var update_time = new Date(update_time).toISOString().slice(0, 19).replace('T', ' ');
      var ifczid = await checkbysql(`select * from qb_sys_user where ID='${id}'`)
      if (!ifczid) {
        await db.update(` insert into qb_sys_user(id, create_by, create_time, update_by,update_time,
           nick_name ,real_name, status, is_deleted, phone,user_type,remark 
          ) 
   values( '${id}', '${create_user}', '${create_time}', '${update_user}', '${update_time}', '${nick_name}', '${real_name}',
    '${status}', '${is_deleted}', '${phone}', '${user_type}', '${remark}'
           )`)
      }
      else {
        await db.update(` update qb_sys_user set create_by='${create_user}',create_time='${create_time}',
        update_by='${update_user}',update_time='${update_time}',nick_name='${nick_name}',
        real_name='${real_name}',status='${status}',is_deleted='${is_deleted}',phone='${phone}',user_type='${user_type}',
        remark='${remark}' where id='${id}'`)
      }
    }
    resolve(1)
  })
}
//同步 t_formula 到 qb_pfjbxxb 配方基本信息表
async function syn_to_qb_pfjbxxb() {
  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id,
    CAST(create_user AS CHAR) AS create_user ,CAST(update_user AS CHAR) AS update_user from t_formula`)
    for (var i = 0; i < rtarr.length; i++) {
      var { id, create_user, create_time, update_user, update_time, formula_code, formula_name, production_line, production_name,
        production_specification, remark, status, is_deleted } = rtarr[i]
      //mysql 日期转换为sql server日期
      var create_time = new Date(create_time).toISOString().slice(0, 19).replace('T', ' ');
      var update_time = new Date(update_time).toISOString().slice(0, 19).replace('T', ' ');
      var ifczid = await checkbysql(`select * from qb_pfjbxxb where ID='${id}'`)
      if (!ifczid) {
        await db.update(` insert into qb_pfjbxxb(id, create_by, create_time, update_by,update_time,
          formula_code ,formula_name, production_line, production_name, production_specification,remark,status,is_deleted
          ) 
   values( '${id}', '${create_user}', '${create_time}', '${update_user}', '${update_time}', '${formula_code}', '${formula_name}',
    '${production_line}', '${production_name}', '${production_specification}', '${remark}', '${status}','${is_deleted}'
           )`)
      }
      else {
        await db.update(` update qb_pfjbxxb set create_by='${create_user}',create_time='${create_time}',
        update_by='${update_user}',update_time='${update_time}',formula_code='${formula_code}',
        formula_name='${formula_name}',production_line='${production_line}',production_name='${production_name}',
        production_specification='${production_specification}',status='${status}',is_deleted='${is_deleted}'
        remark='${remark}' where id='${id}'`)
      }
    }
    resolve(1)
  })
}
//同步 t_formula_design 到 qb_pfsjb 配方设计表
async function syn_to_qb_pfsjb() {
  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id,
  CAST(formula_id AS CHAR) AS formula_id from t_formula_design`)
    for (var i = 0; i < rtarr.length; i++) {
      var { id, formula_id, category } = rtarr[i]
      let design_json = JSON.stringify(rtarr[i].design_json)
      var ifczid = await checkbysql(`select * from qb_pfsjb where ID='${id}'`)
      if (!ifczid) {
        await db.update(` insert into qb_pfsjb(ID,formula_id,category,design_json)
       values( '${id}','${formula_id}','${category}','${design_json}')`)
      }
      else {
        await db.update(` update qb_pfsjb set formula_id='${formula_id}',category='${category}',design_json='${design_json}' where ID='${id}'`)
      }
    }
    resolve(1)
  })
}
//同步 t_formula_structure_design 到 qb_pfjgsjb 配方设计表
async function syn_to_qb_pfjgsjb() {
  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id,
  CAST(formula_id AS CHAR) AS formula_id  from t_formula_structure_design`)
    for (var i = 0; i < rtarr.length; i++) {
      var { id, formula_id, layer, rotate_speed, extrusion_output, ratio } = rtarr[i]
      var ifczid = await checkbysql(`select * from qb_pfjgsjb where ID='${id}'`)
      if (!ifczid) {
        await db.update(` insert into qb_pfjgsjb(ID,formula_id,layer,rotate_speed,extrusion_output,ratio)
       values( '${id}','${formula_id}','${layer}','${rotate_speed}','${extrusion_output}','${ratio}')`)
      }
      else {
        await db.update(` update qb_pfjgsjb set formula_id='${formula_id}',layer='${layer}',rotate_speed='${rotate_speed}',extrusion_output='${extrusion_output}'
      ,ratio='${ratio}' where ID='${id}'`)
      }
    }
    resolve(1)
  })
}


//同步 字典
async function syn_to_qb_gylx_dict_mx() {
  return new Promise(async (resolve, reject) => {

    var db = new Msdb()
    var mysqldb = new Mysqldb()
    var rtarr = await mysqldb.query(`select *,CAST(id AS CHAR) AS id  from sys_dict_data`)
    for (var i = 0; i < rtarr.length; i++) {
      var { id, dict_code, dict_label, dict_value } = rtarr[i]
      var ifczid = await checkbysql(`select * from qb_gylx_dict_mx where ID='${id}'`)
      if (!ifczid) {
        await db.update(` insert into qb_gylx_dict_mx (id,dict_code,dict_label,dict_value)
       values( '${id}','${dict_code}','${dict_label}','${dict_value}')`)
      }
      else {
        await db.update(` update qb_gylx_dict_mx 
        set dict_code='${dict_code}',dict_label='${dict_label}',dict_value='${dict_value}'
   where ID='${id}'`)
      }
    }
    resolve(1)
  })
}

//更改工单状态为延期
async function updateGdStatus() {
  return new Promise(async (resolve, reject) => {
    var db = new Msdb()

    let sql = `select glgylxid,djh,id from qb_gd where wgrq is not NULL and wgrq<GETDATE() and djzt='正常'`

    let result = await db.query(sql)
    for (var i = 0; i < result.recordsets[0].length; i++) {
      let formdata = result.recordsets[0][i]
      let workOrderJson = []
      try {
        //插入到工单历史表
        await db.update(`insert into qb_gd_history (id,create_time,create_by,mainid,gdh,gdzt)
      VALUES (next value for seq_id,getdate(),'admin','${formdata.id}','${formdata.djh}','延期')`)
      }
      catch (error) {
        logger.info("更新工单状态为延期失败", error)
      }
      workOrderJson.push({ "workOrderCode": formdata.djh, "workOrderStatus": '延期' })
      if (formdata.glgylxid !== '' && formdata.glgylxid !== 'null' && formdata.glgylxid !== undefined && formdata.glgylxid !== "undefined") {
        try {
          await api_gd_to_gylx(formdata.glgylxid, JSON.stringify(workOrderJson))
        } catch (error) {
          logger.info("调用出错啦", error)
        }
      }
    }


    await db.update(`update qb_gd set djzt='延期' where wgrq is not NULL and wgrq<GETDATE() and djzt='正常'`)
    await db.update(`update qb_gd_fqmx set djzt='延期' where wgrq is not NULL and wgrq<GETDATE() and djzt='正常'`)
    // await db.update(`update qb_gd_mjmx set djzt='延期' where wgrq is not NULL and wgrq<GETDATE() and djzt='正常'`)
    resolve(1)
  })
}

// // 创建计划任务  每隔两个小时同步人员一次
// Schedule.scheduleJob("0 */2 * * *", function () {
//   // 在这里编写你想要执行的代码  
//   ygdaSync()
//   syn_to_qb_gxmb()
//   syn_to_qb_gxmb_mx()
//   syn_to_qb_gy()
//   syn_to_qb_gy_mx()
//   syn_to_qb_gylx()
//   syn_to_qb_gylx_mx()
//   syn_to_qb_gyzlxf()
//   syn_to_qb_gyzlxf_mx()
//   syn_to_qb_sys_user()
//   syn_to_qb_pfjbxxb()
//   syn_to_qb_pfsjb()
//   syn_to_qb_pfjgsjb()
//   syn_to_qb_gylx_dict_mx()
// });

// // 创建计划任务  每天的凌晨三点执行同步一次部门
// Schedule.scheduleJob("0 3 * * *", function () {
//   // 在这里编写你想要执行的代码  
//   bmSync()
// });

// // 创建计划任务  每天的凌晨三点执行同步一次部门
// Schedule.scheduleJob("0 0 * * *", function () {
//   // 在这里编写你想要执行的代码  
//   updateGdStatus()
// });




var server = app.listen(7777, async function () {
  var host = 'localhost'
  var port = server.address().port
  console.log("应用实例，访问地址为 http://%s:%s", host, port);
  // var db=new Mysqldb("fsdfsdfsdf");

  logger.info("最大配置内存为" + require("v8").getHeapStatistics().total_available_size / 1024 / 1024)

  // setInterval(async() => {
  //   var jskclock=  await Redisdb.get_async("jskc")
  //   if(jskclock){
  //       console.log("不同步")
  //       await Redisdb.del_async("jskc")

    
  //   }
  //   else{
  //     await Redisdb.set_async("jskc","23232")
  //     await tbjsshipSRM_util();
  //       await Redisdb.del_async("jskc")
    
  //   }
    
  // }, 1000 * 60 * 10)


})

